package main

import (
	"fmt"
	"os"
	"os/exec"
	"runtime"
	"strings"
	"time"
)

// runByDaemon 以daemon的方式启动程序，并监控进程
func runByDaemon(args []string) {
	fmt.Printf("PID: %d PPID: %d ARG: %s\n", os.Getpid(), os.Getppid(), os.Args)
	//去掉-daemon运行参数，启动主程序
	for i := 0; i < len(args); {
		if args[i] == "-daemon" && i != len(args)-1 {
			args = append(args[:i], args[i+1:]...)
		} else if args[i] == "-daemon" && i == len(args)-1 {
			args = args[:i]
		} else {
			i++
		}
	}
	//启动子进程,去掉-daemon参数后，执行程序，由于子程序无daemon参数，因此会直接执行业务代码
	for {
		cmd := exec.Command(args[0], args[1:]...)
		cmd.Stdin = os.Stdin
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		err := cmd.Start() //开启子进程
		if err != nil {
			_, _ = fmt.Fprintf(os.Stderr, "start oasis erir [-] Error: %s\n", err)
			return
		}
		fmt.Println("run oasis by daemon,pid=", cmd.Process.Pid, ",ppid=", os.Getpid(), "args=", args, "time=", time.Now())
		_ = cmd.Wait() //阻塞等待进程退出
		time.Sleep(time.Duration(time.Second))
	}
}

func runInWindows(cmd string) (string, error) {
	result, err := exec.Command("cmd", "/c", cmd).Output()
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(result)), err
}

func runInLinux(cmd string) (string, error) {
	fmt.Println("Running Linux cmd:" + cmd)
	result, err := exec.Command("/bin/sh", "-c", cmd).Output()
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(result)), err
}

func RunCommand(cmd string) (string, error) {
	if runtime.GOOS == "windows" {
		return runInWindows(cmd)
	} else {
		return runInLinux(cmd)
	}
}

// CheckProRunning 根据进程名判断进程是否运行
func CheckProRunning(serverName string) (bool, error) {
	a := `ps ux | awk '/` + serverName + `/ && !/awk/ {print $2}'`
	pid, err := RunCommand(a)
	if err != nil {
		return false, err
	}
	return pid != "", nil
}

// GetPid 根据进程名称获取进程ID
func GetPid(serverName string) (string, error) {
	a := `ps ux | awk '/` + serverName + `/ && !/awk/ {print $2}'`
	pid, err := RunCommand(a)
	return pid, err
}
